<template>
  <div class="relative w-full h-full">
    <PageHeader :title="$t('comment.评价管理')" />
    <div class="flex_aic_jcsb flex-wrap gap-3">
      <div class="flex_aic gap-12">
        <el-input
          v-model="searchForm.productName"
          :placeholder="$t('comment.请输入商品名称')"
          style="width: 220px"
        >
          <template #prefix>
            <span class="color-555555">{{ $t('comment.商品名称') }}</span>
          </template>
        </el-input>

        <el-input
          v-model="searchForm.userName"
          :placeholder="$t('comment.请输入用户名称')"
          style="width: 220px"
        >
          <template #prefix>
            <span class="color-555555">{{ $t('comment.用户名称') }}</span>
          </template>
        </el-input>

        <el-date-picker
          v-model="searchForm.dateRange"
          type="daterange"
          :range-separator="$t('comment.至')"
          :start-placeholder="$t('comment.评价开始日期')"
          :end-placeholder="$t('comment.评价结束日期')"
          style="width: 320px"
        />

        <el-select
          v-model="searchForm.status"
          :placeholder="$t('comment.评价状态')"
          style="width: 150px"
        >
          <el-option :label="$t('comment.全部')" value="all" />
          <el-option
            v-for="item in commentStatusOptions"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
      </div>

      <div class="flex_aic">
        <el-button @click="resetSearch">{{ $t('comment.重置') }}</el-button>
        <el-button type="primary" @click="handleSearch">{{ $t('comment.查询') }}</el-button>
      </div>
    </div>

    <el-table
      :data="tableData"
      style="width: 100%"
      class="cover-table mt12"
      border
      v-loading="loading"
      height="calc(100% - 160px)"
    >
      <el-table-column prop="title" :label="$t('comment.商品信息')" width="500">
        <template #default="{ row }">
          <div class="flex">
            <el-popover placement="right" width="226" trigger="hover">
              <div
                class="bigImg"
                :style="`background-image: url(${row.skuSpecDetailImage})`"
              ></div>
              <template #reference>
                <div
                  class="goodImg"
                  :style="`background-image: url(${row.skuSpecDetailImage})`"
                ></div>
              </template>
            </el-popover>

            <div class="ml10 flex_fdc_jcsb text-left">
              <div class="color-333333 line-2">
                {{ row["skuName" + locale] }}
              </div>
              <div class="color-666666 fs-12">
                <div class="line-1">
                  {{ row["skuClassify1Name" + locale] }}->{{
                    row["skuClassify2Name" + locale]
                  }}
                </div>
                <div class="line-1">
                  {{ $t('comment.所属店铺') }}：{{ row["tenantName" + locale] }}
                </div>
              </div>
              <div class="color-666666 fs-12 line-2">
                {{ row.skuSpecDetail.map(v=> `${v['specName' + locale]}:${v['specDetailName' + locale]}`)?.join(',') }}
              </div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="comment" :label="$t('comment.评价描述')" min-width="200">
        <template #default="{ row }">
          <div>
            <div class="flex">
              <div class="flex-shrink-0">{{ $t('comment.商品评分') }}：</div>
              <el-rate :model-value="row.commentStars" />
            </div>
            <div class="flex">
              <div class="flex-shrink-0">{{ $t('comment.评价内容') }}：</div>
              <div class="text-left">{{ row.commentContent }}</div>
            </div>
            <div class="flex mt12">
              <div class="flex-shrink-0">{{ $t('comment.晒单照片') }}：</div>
              <div class="flex_aic flex-wrap gap-6" v-if="row.commentImage">
                <div v-for="(img, index) in row.commentImage.split(',')" :key="index">
                  <video :src="img" v-if="img.includes('.mp4')" style="width: 40px; height: 40px" @click="previewVideo(img)"></video>
                  <el-image
                    v-else
                    style="width: 40px; height: 40px"
                    :src="img"
                    :zoom-rate="1.2"
                    :max-scale="7"
                    :min-scale="0.2"
                    :preview-src-list="[img]"
                    show-progress
                    :initial-index="0"
                    fit="cover"
                    preview-teleported
                  />
                </div>
              </div>
            </div>
            <div v-if="row.commentStatus == 2" class="flex mt12">
              <div class="flex-shrink-0">{{ $t('comment.商家回复') }}：</div>
              <div class="text-left">{{ row.replyContent }}</div>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="vipNickName" :label="$t('comment.评价人')" width="120" />

      <el-table-column prop="commentTime" :label="$t('comment.评价时间')" width="160">
        <template #default="{ row }">
          {{
            row.commentTime
              ? moment(row.commentTime).format("YYYY-MM-DD HH:mm:ss")
              : "--"
          }}
        </template>
      </el-table-column>

      <el-table-column prop="status" :label="$t('comment.状态')" width="240">
        <template #default="{ row }">
          <el-tag
            :type="commentStatusMap[row.commentStatus]?.type"
            class="myTag"
          >
            {{ commentStatusMap[row.commentStatus]?.label }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column :label="$t('comment.操作')" width="160" fixed="right">
        <template #default="scope">
          <div class="operationBtnRow">
            <el-button v-if="scope.row.commentStatus == 1" type="text" size="small" @click="handleReply(scope.row)" v-my-point="'saleSku:commentReply'"
              >{{ $t('comment.回复') }}</el-button
            >
            <el-button
              type="text"
              size="small"
              @click="handleViewDetail(scope.row)"
              >{{ $t('comment.查看详情') }}</el-button
            >
            <!-- <el-popconfirm
              :title="$t('comment.确定删除吗？')"
              @confirm="handleDelete(scope.row)"
              :confirm-button-text="$t('comment.确定')"
              :cancel-button-text="$t('comment.取消')"
              width="260px"
            >
              <template #reference>
                <el-button class="ml0" type="text" size="small">{{ $t('comment.删除') }}</el-button>
              </template>
            </el-popconfirm> -->
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div class="flex justify-end mt24 absolute bottom-0 right-0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 回复弹窗 -->
    <Dialog
      v-model="replyDialogVisible"
      :title="$t('comment.回复评价')"
      width="500px"
      @confirm="submitReply"
      :confirmLoading="replyLoading"
    >
      <el-form
        :model="replyForm"
        :rules="replyRules"
        label-width="80px"
        ref="replyFormRef"
      >
        <el-form-item :label="$t('comment.回复评价')" prop="content">
          <el-input
            v-model="replyForm.content"
            type="textarea"
            rows="4"
            :placeholder="$t('comment.请输入回复内容')"
          />
        </el-form-item>
      </el-form>
    </Dialog>

    <!-- 查看详情弹窗 -->
    <Dialog
      v-model="detailDialogVisible"
      :title="$t('comment.评价详情')"
      width="700px"
      @confirm="() => (detailDialogVisible = false)"
    >
      <div class="detail-container">
        <div class="product-info flex_aic mb4 pb4 border-bottom">
          <el-image
            style="width: 80px; height: 80px"
            :src="currentComment.skuSpecDetailImage"
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            :preview-src-list="[currentComment.skuSpecDetailImage]"
            show-progress
            :initial-index="4"
            fit="cover"
            preview-teleported
            class="flex-shrink-0"
          />
          <div class="ml12 flex_fdc_jcsb text-left">
            <div class="color-333333 line-2">
              {{ currentComment["skuName" + locale] }}
            </div>
            <div class="color-666666 fs-12">
              <div class="line-1">
                {{ currentComment["skuClassify1Name" + locale] }}->{{
                  currentComment["skuClassify2Name" + locale]
                }}
              </div>
              <div class="line-1">
                {{ $t('comment.所属店铺') }}：{{ currentComment["tenantName" + locale] }}
              </div>
            </div>
            <div class="color-666666 fs-12 line-2">
              {{ currentComment.skuSpecDetail.map(v=> `${v['specName' + locale]}:${v['specDetailName' + locale]}`)?.join(',') }}
            </div>
          </div>
        </div>

        <div class="comment-section mt20 mb4 pb4 border-bottom">
          <div class="mb2 font-bold">用户评价</div>
          <div class="user-info flex_aic mb2">
            <span class="color-666666 mr3">{{
              currentComment.vipNickName
            }}</span>
            <span class="color-666666">{{
              currentComment.commentTime
                ? moment(currentComment.commentTime).format(
                    "YYYY-MM-DD HH:mm:ss"
                  )
                : "--"
            }}</span>
          </div>
          <div class="mb12">{{ currentComment.commentContent }}</div>
          <div class="flex_aic flex-wrap" v-if="currentComment.commentImage">
            <div
              v-for="(img, index) in currentComment.commentImage.split(',')"
              :key="index"
            >
              <video
                :src="img"
                :controls="false"
                style="width: 80px; height: 80px"
                v-if="img.includes('.mp4')"
                @click="previewVideo(img)"
              ></video>
              <el-image
                v-else
                style="width: 80px; height: 80px"
                :src="img"
                :zoom-rate="1.2"
                :max-scale="7"
                :min-scale="0.2"
                :preview-src-list="[img]"
                show-progress
                :initial-index="4"
                fit="cover"
                preview-teleported
                class="flex-shrink-0"
              />
            </div>
          </div>
        </div>

        <div class="reply-section" v-if="currentComment.replyContent">
          <div class="mb2 font-bold">商家回复</div>
          <div class="user-info flex_aic mb2">
            <span class="color-666666 mr3">商家</span>
            <span class="color-666666">{{
              currentComment.replyTime
                ? moment(currentComment.replyTime).format("YYYY-MM-DD HH:mm:ss")
                : "--"
            }}</span>
          </div>
          <div>{{ currentComment.replyContent }}</div>
        </div>
      </div>
    </Dialog>

    <el-image-viewer
      v-if="previewVisible"
      :url-list="currentImages"
      :initial-index="previewIndex"
      @close="previewVisible = false"
    />

    <!-- 视频预览对话框 -->
    <el-dialog v-model="showVideoDia" :title="$t('uploadVideo.视频预览')" width="800px">
      <div class="flex_aic_jcc w-full h-full">
        <video
          :src="videoSrc"
          controls
          style="max-width: 80%; max-height: 500px;"
          v-if="videoSrc"
        ></video>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import Dialog from "@/components/dialog.vue";
import Api from "@/config/api/api";
import { onMounted } from "vue";
import { useI18n } from "vue-i18n";
import moment from "moment";
import i18n from "@/i18n";
import { useRoute } from "vue-router";

const route = useRoute()
const { locale, t } = useI18n();
const langs = reactive(Object.keys(i18n.global.messages.value));
// 搜索表单
const searchForm = reactive({
  productName: "",
  userName: "",
  dateRange: [],
  status: route.query?.status ?? "all",
});
const showVideoDia = ref(false)
const videoSrc = ref("")
const previewVideo = (src)=>{
  showVideoDia.value = true
  videoSrc.value = src
}

// -1已删除 0待评论 1已评论 2已回复
const commentStatusMap = {
  "-1": {
    label: t('comment.已删除'),
    type: "danger",
  },
  /*0: {
    label: "待评论",
    type: "warning",
  },*/
  1: {
    label: t('comment.待回复'),
    type: "primary",
  },
  2: {
    label: t('comment.已回复'),
    type: "success",
  },
};
const commentStatusOptions = Object.keys(commentStatusMap).map((k) => ({
  label: commentStatusMap[k].label,
  value: k,
}));
// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(100);

// 表格数据
const tableData = ref([]);
const loading = ref(false);

// 回复弹窗相关
const replyDialogVisible = ref(false);
const currentComment = ref({});

const replyForm = reactive({
  content: "",
});
const replyFormRef = ref()
const replyLoading = ref(false)
const replyRules = ref({
  content: [{ required: true, message: "请输入回复评价", trigger: "blur" }],
});

// 详情弹窗
const detailDialogVisible = ref(false);

// 重置搜索条件
const resetSearch = () => {
  searchForm.productName = "";
  searchForm.userName = "";
  searchForm.dateRange = [];
  searchForm.status = "";
  currentPage.value = 1;
  getDataList();
};

// 查询
const handleSearch = () => {
  currentPage.value = 1;
  getDataList();
};

// 页码变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  getDataList();
};

// 页数变化
const handleCurrentChange = (page) => {
  currentPage.value = page;
  getDataList();
};

// 处理删除评价
const handleDelete = (row) => {
  console.log("删除评价", row.id);
  // 实际应调用API删除
};

// 处理回复评价
const handleReply = (row) => {
  currentComment.value = row;
  replyForm.content = "";
  replyDialogVisible.value = true;
};

// 提交回复
const submitReply = () => {
  replyFormRef.value.validate((valid, fields) => {
    if (valid) {
      replyLoading.value = true
      Api.commentReply({
        id: currentComment.value.id,
        replyContent: replyForm.content,
      }).then((res) => {
        if (res.status === 200) {
          ElMessage.success("回复成功");
          replyDialogVisible.value = false;
          getDataList();
        }
      }).finally(el=>{
        replyLoading.value = false
      });
    }
  });
};

// 查看详情
const handleViewDetail = (row) => {
  currentComment.value = row;
  detailDialogVisible.value = true;
};

const previewVisible = ref(false);
const currentImages = ref([]);
const previewIndex = ref(0);

const handlePreviewImage = (img, images) => {
  // currentImages.value = images;
  // previewIndex.value = images.indexOf(img);
  // previewVisible.value = true;
};

const getDataList = () => {
  loading.value = true;
  const params = {
    page: currentPage.value - 1,
    size: pageSize.value,
    commentStatus: searchForm.status === "all" ? "" : searchForm.status,
    commentType: 1,
    vipNickName: searchForm.userName,
    commentTimeStart: searchForm.dateRange[0] ? moment(searchForm.dateRange[0]).format("YYYY-MM-DD 00:00:00") : undefined,
    commentTimeEnd: searchForm.dateRange[1] ? moment(searchForm.dateRange[1]).format("YYYY-MM-DD 23:59:59") : undefined,
    ["skuName" + locale.value]: searchForm.productName,
    // commentStatusNE: -1
    commentStatuses: [1, 2]
  };
/*  langs.forEach((el) => {
    params[`skuName${el}`] = searchForm.productName;
  });*/
  Api.saleSku_list(params).then((res) => {
    tableData.value = res.data.content || [];
    total.value = Number(res.data.totalElements || 0);
    loading.value = false;
  });
};

onMounted(() => {
  getDataList();
});
</script>

<style lang="scss" scoped>
.product-name {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.border-bottom {
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.mt12 {
  margin-top: 12px;
}

.mt24 {
  margin-top: 24px;
}
.goodImg {
  display: inline-block;
  flex-shrink: 0;
  width: 80px;
  height: 80px;
  overflow: hidden;
  border: 1px solid #e2e5f6;
  border-radius: 3px;
  background: #f8f8f8;
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
}

.bigImg {
  display: inline-block;
  flex-shrink: 0;
  width: 200px;
  height: 200px;
  overflow: hidden;
  // border: 1px solid #e2e5f6;
  // border-radius: 3px;
  // background: #f8f8f8;
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
}

:deep(.myTag) {
  &.el-tag--primary {
    color: #409eff;
  }
}
</style>
